package org.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;


//服务端 服务容器类 用来存储服务实例 在这里统一管理
//这里默认是linkedHashset 因为要保证顺序+去重
@Service
public class ServiceContext {

    @Autowired
    private DiscoveryService discoveryService;

    // 使用 ConcurrentHashMap 线程安全地存储服务实例
    private final ConcurrentMultimap<String, ServiceInstance> serviceMap =
            new ConcurrentMultimap<>(LinkedHashSet::new);


    //初始化这个服务列表
    @PostConstruct
    public void initServiceMap() {
        serviceMap.checkType();
        System.out.println("注册监听者并 初始化服务列表");
        Map<String, Collection<ServiceInstance>> remoteMap = discoveryService.registerAndGetServices();
//
        addAllServices(remoteMap);
        System.out.println("初始化服务列表完成 服务数量为:" + getServiceCount());
        serviceMap.checkType();

    }


    // 上线服务
    public void login(ServiceInstance serviceInstance) {
        addService(serviceInstance);
        System.out.println("上线服务:" + serviceInstance);
    }

    //下线服务
    public void logout(ServiceInstance serviceInstance) {
        removeServicesByServiceInstance(serviceInstance);
        System.out.println("下线服务 :" + serviceInstance);

    }


    //以下是公共的

    // 获取服务列表 这里是set
    public Collection<ServiceInstance> getServices(String serviceName) {
        return serviceMap.get(serviceName);
    }

    // 获取所有服务
    public ConcurrentMultimap<String, ServiceInstance> getAllServices() {
        return serviceMap;
    }


    //移除服务 从集合中移除
    public void removeServicesByServiceInstance(ServiceInstance serviceInstance) {
        String serviceName = serviceInstance.getServiceName();
        if (!serviceMap.containsKey(serviceName)) {
            return;
        }
        Collection<ServiceInstance> serviceInstances = serviceMap.get(serviceName);
        serviceInstances.remove(serviceInstance);
    }

    //添加服务
    public void addService(ServiceInstance serviceInstance) {
        serviceMap.putValue(serviceInstance.getServiceName(), serviceInstance);
    }

    //添加所有服务
    public void addAllServices(Map<String, Collection<ServiceInstance>> services) {
        serviceMap.putAll(services);
    }


    //获取服务数量 要累加每个集合的大小
    public int getServiceCount() {
        int count = 0;
        //遍历键值对
        for (Map.Entry<String, Collection<ServiceInstance>> entry : serviceMap.entrySet()) {
            count += entry.getValue().size();
        }
        return count;
    }

}
